const { resolve } = require('path')

const { jgcl } = require(resolve(__dirname, '../../utils/utils'))

const Praise = require('../../database/dbModule/praise')

// 查询点赞
const praiseSelect = async (ctx) => {
  const data = ctx.query
  const {
    categoryName = null,
    pageNum = 1, // 页数
    pageSize = 10, // 数据条数
  } = data

  try {

    const num = await Categories.find({ isDel: false }).count()

    if (categoryName === null || categoryName === '') {
      const findRes = await Categories.find({ isDel: false })
        .skip(pageSize * (pageNum - 1))
        .limit(pageSize)

      if (findRes === null) {
        jgcl(ctx, 2015, '点赞数据为空!')
      } else {
        jgcl(ctx, 200, '查询成功!', { total: num, list: findRes })
      }
    } else {
      const findRes = await Categories.find(
        {
          categoryName: { $regex: new RegExp(categoryName) },
          isDel: false
        }
      ).skip(pageSize * (pageNum - 1))
        .limit(pageSize)


      if (findRes.length === 0) {
        jgcl(ctx, 2012, '点赞数据为空!')
      } else {
        jgcl(ctx, 200, '查询成功!', { total: num, list: findRes })
      }
    }

  } catch (err) {
    jgcl(ctx, 2014, '查询失败!', err)
  }
}

// 点赞
const praise = async (ctx) => {
  const data = ctx.request.body
  const {
    userId,
    title,
    articleId,
    status,
    isDel = false
  } = data
  console.log(data)

  try {
    const findRes = await Praise.findOne({ title, isDel: false })
    if (findRes === null) {
      const creatRes = await Praise.create({
        userId,
        title,
        articleId,
        status,
        isDel
      })
      jgcl(ctx, 200, '点赞完成!')
    } else {
      const findRes = await Praise.findOne({ userId, isDel: false })
      if (userId === null) {
        const creatRes = await Praise.create({
          userId,
          title,
          articleId,
          status,
          isDel
        })
        jgcl(ctx, 2012, '点赞完成!')
      } else {
        const upRes = await Praise.updateOne({ isDel: false, articleId }, { status })
        jgcl(ctx, 200, '点赞完成!')
      }
    }

  } catch (err) {
    jgcl(ctx, 2016, '点赞失败!', err)
    console.log(err)

  }

}

// 查
const findPraise = async (ctx) => {
  try {
    const {
      userId,
      articleId = "",
    } = ctx.query
    console.log(userId, articleId)

    const findRes = await Praise.findOne({ userId, articleId, isDel: false })
    jgcl(ctx, 200, '查询成功!', findRes)

  } catch (err) {
    jgcl(ctx, 200, '查询成功!', { err })
    console.log(err)
  }


}

// 查数量
const findPraiseNum = async (ctx) => {
  try {
    const { title } = ctx.query
    const num = await Praise.find({ title, status: true, isDel: false }).count()
    jgcl(ctx, 200, '查询成功!', num)
  } catch (err) {
    jgcl(ctx, 2014, '查询失败!')
  }
}

module.exports = {
  praise,
  findPraise,
  findPraiseNum
}